package com.example.cloud.config.web;

import com.alibaba.fastjson.JSON;
import com.example.cloud.service.system.UserService;
import com.example.cloud.utils.ResultUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Created by wangtao on 2018/5/31.
 */
@Aspect
@Configuration
public class AopConfig {

    public static final Logger logger = LoggerFactory.getLogger(AopConfig.class);

    @Autowired
    private UserService userService;

    /**
     * 控制器拦截
     */
    @Pointcut("within(com.example.cloud.controller..*)")
    public void controllerPointcut() {
    }

    @Before("controllerPointcut()")
    public void before(JoinPoint joinPoint) throws Throwable {
        // TODO 校验用户状态
        // TODO 可以添加日志服务方便监控

    }

    @Around("controllerPointcut()")
    public Object arround(ProceedingJoinPoint pjp) throws Exception {
        Object result = null;// 返回结果
        HttpServletResponse response = getHttpServletResponse();
        try {
            result = pjp.proceed();
            if (result == null) {
                result = ResultUtil.success("操作成功");
                response.getWriter().write(JSON.toJSONString(result));
            }
        } catch (Throwable e) {
            result = ResultUtil.fail("操作异常");
            response.getWriter().write(JSON.toJSONString(result));
            logger.error("系统异常：[" + getMethodInfo(pjp) + "],异常信息：" + e.getMessage(), e);
        }
        return result;
    }

    /**
     * 获取HttpServletResponse
     * @return
     */
    public HttpServletResponse getHttpServletResponse(){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        return response;
    }

    /**
     * 获取本次请求方法具体信息
     * @param point
     * @return
     */
    public String getMethodInfo(ProceedingJoinPoint point) {
        String className = point.getSignature().getDeclaringType().getSimpleName();
        String methodName = point.getSignature().getName();
        String[] parameterNames = ((MethodSignature) point.getSignature()).getParameterNames();
        StringBuilder sb = new StringBuilder();
        if (Objects.nonNull(parameterNames)) {
            for (int i = 0; i < parameterNames.length; i++) {
                String value = point.getArgs()[i] != null ? point.getArgs()[i].toString() : "null";
                sb.append(parameterNames[i] + ":" + value + "; ");
            }
        }
        return String.format("class:%s | method:%s | args:%s", className, methodName, sb.toString());
    }
}
